package models

import (
	"errors"
	"time"

	"gorm.io/gorm"
)

type SysDept struct {
	ID           int64      `json:"id" gorm:"primaryKey"` // 菜单id
	ParentID     int64      `json:"parentId"`             // 父id
	DeptName     string     `json:"deptName"`             // 名称
	ShowOrder    int        `json:"showOrder"`            // 在线表单主键Id，仅用于在线表单绑定的菜单。
	CreateTime   *time.Time `json:"createTime"`
	CreateUserID int64      `json:"createUserId"`
	UpdateTime   *time.Time `json:"updateTime"`
	UpdateUserID int64      `json:"updateUserId"`
	DeletedFlag  int        `json:"deletedFlag"` // 1正常 -1 已经删除
	Children     []*SysDept `json:"children" gorm:"-"`
}

func GetAllDeptTree(parentId int64, depth int) []*SysDept {
	if depth == 0 {
		return make([]*SysDept, 0)
	}
	var nodes []*SysDept
	_ = db.Where("parent_id = ?", parentId).Find(&nodes).Error
	for _, node := range nodes {
		node.Children = GetAllDeptTree(node.ID, depth-1)
	}
	return nodes
}

func GetAllDeptList(dept_name string, page, pageSize int) ([]SysDept, int64, error) {
	var depts []SysDept
	limit := pageSize
	var total int64
	var err error
	offset := pageSize * (page - 1)
	dbQuery := db.Offset(offset).Limit(limit).Order("show_order desc")
	if dept_name != "" {
		dbQuery.Where("dept_name like ?", "%"+dept_name+"%")
	}
	err = dbQuery.Find(&depts).Error
	err = db.Model(&SysDept{}).Count(&total).Error
	return depts, total, err
}

func AddSysDept(dept SysDept) error {
	if !errors.Is(db.Where("dept_name = ?", dept.DeptName).First(&SysDept{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("相同名称部门已经存在，无法添加")
	}
	return db.Create(&dept).Error
}

func GetASysDept(id int64) (*SysDept, error) {
	var sysDept SysDept
	err := db.Where("id = ?", id).First(&sysDept).Error
	return &sysDept, err
}

func UpdateSysDept(e *SysDept) (err error) {
	err = db.Save(e).Error
	return err
}

func DeleteDept(id int) (err error) {
	var dept SysDept
	return db.Where("`id` = ?", id).Delete(&dept).Error
}
